# -*- coding:utf-8 -*-

import logging
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView

from Apps.Interface.models.interfaceCat import InterfaceCat
from Apps.Interface.models.interface import Interface
from Apps.Interface.ser.interfaceCatSer import InterfaceCatSer
from Apps.Interface.ser.interfaceSer import CatInterfaceSer
from Apps.common.response import SuccessResponse, ErrorResponse

logger = logging.getLogger('django')


class InterfaceCatView(ModelViewSet):
    serializer_class = InterfaceCatSer
    queryset = InterfaceCat.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return SuccessResponse(serializer.data)

    def create(self, request, *args, **kwargs):
        request.data["modifier"] = request.user.id
        request.data["creator"] = request.user.id
        request.data["index_num"] = '-1'
        parent_list = request.data["parent"]
        if not parent_list:
            request.data["parent"] = ""
        else:
            request.data["parent"] = parent_list[-1]
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return SuccessResponse(serializer.data, headers=headers)

    def perform_create(self, serializer):
        serializer.save()


class interfaceCatOptionsInterfaceView(APIView):
    authentication_classes = []

    # 递归获取子分类
    def getChildren(self, cat_all: list, cat_queryset: list):

        for cat in cat_queryset:
            cat_list = {}
            children = []

            cat_list["id"] = cat.id
            cat_list["label"] = cat.category_name
            cat_list["index"] = cat.index_num

            # type, expand  作为前端调整的数据，不在后端储存
            cat_list["type"] = "cat"
            cat_list["expand"] = False

            cat_queryset = InterfaceCat.objects.filter(parent=cat.id)
            # 如果有子分类的情况，继续获取分类
            if len(cat_queryset) != 0:
                children = self.getChildren(children, cat_queryset)
                cat_list["children"] = children
                interface_queryset = Interface.objects.filter(interface_category=cat.id)
                if len(interface_queryset) != 0:
                    serializer = CatInterfaceSer(interface_queryset, many=True)
                    for item in serializer.data:
                        cat_list["children"].append(item)

            # 如果没有子分类，去查询当前分类下的接口
            if len(cat_queryset) == 0:
                interface_queryset = Interface.objects.filter(interface_category=cat.id)
                serializer = CatInterfaceSer(interface_queryset, many=True)
                cat_list["children"] = serializer.data

            cat_all.append(cat_list)

        logger.info("======获取的分类数据（包括接口）=====")
        return cat_all

    # pk 根据项目id 查询分类=>最小子分类查询接口
    def get(self, request, *args, **kwargs):
        cat_queryset = InterfaceCat.objects.filter(parent="").filter(project=kwargs["pk"])
        cat_all = []
        cat_data = self.getChildren(cat_all, cat_queryset)
        return SuccessResponse(cat_data)


class interfaceCatOptionsView(APIView):

    def getChildren(self, cat_all, cat_queryset):
        for cat in cat_queryset:
            cat_list = {}
            children = []

            cat_list["value"] = cat.id
            cat_list["label"] = cat.category_name
            cat_list["index"] = cat.index_num
            cat_queryset = InterfaceCat.objects.filter(parent=cat.id)

            # 如果有子分类的情况，继续获取分类
            if len(cat_queryset) != 0:
                children = self.getChildren(children, cat_queryset)
                cat_list["children"] = children

            cat_all.append(cat_list)

        logger.info("======获取的分类数据（仅分组，用于创建分组）=====")
        return cat_all

    def get(self, request, *args, **kwargs):
        cat_queryset = InterfaceCat.objects.filter(parent="").filter(project=kwargs["pk"])
        cat_all = []
        cat_data = self.getChildren(cat_all, cat_queryset)
        return SuccessResponse(cat_data)
